import axios, { AxiosError, AxiosInstance, AxiosResponse, CreateAxiosDefaults } from "@ohos/axios"
// import {get} from "func"
class Request{
  private instance:AxiosInstance
  constructor(config:CreateAxiosDefaults) {
    this.instance=axios.create(config)
    this.beforeRequest()
    this.beforeResponse()
  }

  // 拦截
  // 请求拦截
  private beforeRequest(){
    this.instance.interceptors.request.use((req)=>{
      // console.log('请求拦截')
      let token=AppStorage.get("token")
      // console.log(JSON.parse(token as string)+'')
      if(token){
        token=JSON.parse(token as string)
        let userinfo=JSON.parse(AppStorage.get("userinfo"))
        req.headers.Authorization=token as string
        req.headers.userId=userinfo.pid
      }

      return req
    })
  }
  // 响应拦截
  private beforeResponse(){
    this.instance.interceptors.response.use((res)=>{
      return res
    },(err:AxiosError)=>{
      console.log(JSON.stringify(err))
      if(err.status==404){

      }else if(err.status==401){

      }
      return {}
    })
  }

  // 请求方式 get post delete put
  // AxiosResponse 后台返回结果的数据类型
  post(url:string,data?):Promise<AxiosResponse>{
    return this.instance.post(url,data)
  }
  // 键值对 {key:val} => url?key=val&key=val
  // params axios提供params获取参数 把他通过 问号传参 拼接到路径上
  get(url:string,data?):Promise<AxiosResponse>{
    return this.instance.get(url,{params:data})
  }
}

export default Request